package com.szrt.java.book.utils;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class BookUtil {
	
	
	
	/**
	 * 美化打印效果
	 * @return
	 */
	public static OutputFormat getOutputFormat(){
		OutputFormat format = OutputFormat.createPrettyPrint();
		
		//2 设置XML编码方式,即是用指定的编码方式保存XML文档到字符串(String),这里也可以指定为GBK或是ISO8859-1
		format.setEncoding("utf-8");
		//format.setSuppressDeclaration(true); //是否生产xml头
		format.setIndent(true);   //设置是否缩进
		format.setIndent("\t");   // 以四个空格方式实现缩进
		format.setNewlines(true); // 设置是否换行
		return format;
	}
	
	
	/**
	 * 把xml文档打印到控制台
	 * @param document
	 */
	public static void print(Document document) throws Exception{
		//stringWriter字符串是用来保存XML文档的
		StringWriter stringWriter = new StringWriter();
		// xmlWriter是用来把XML文档写入字符串的(工具)
		XMLWriter xmlWriter = new XMLWriter(stringWriter, getOutputFormat());

		// 把创建好的XML文档写入字符串
		xmlWriter.write(document);

		// 打印字符串,即是XML文档
		System.out.println(stringWriter);

		xmlWriter.close();
	}
	
	
	
	public static void  add(Document document,String file) throws Exception{
		PrintWriter pw = new PrintWriter(file);  
        XMLWriter xw = new XMLWriter(pw,getOutputFormat());  
        xw.write(document);  
        xw.flush();  
        xw.close();  
	}

}
